package org.sxpcwlkj.signdemo.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.sxpcwlkj.signdemo.entity.MemberEntity;
import org.sxpcwlkj.signdemo.properties.SignProperties;
import org.sxpcwlkj.signdemo.utils.RequestEntity;
import org.sxpcwlkj.signdemo.utils.SignPlusUtils;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController {

    @Autowired
    private SignProperties signProperties;



    @GetMapping("test")
    public Object httpRequsetTset(){

        String appId = "000000001";
        String apiUrl = "http://192.168.31.114:9200/property/api/v1/getMemberInfo";

        String publicKey = signProperties.getPublicKey();

        //参数签名测试例子
        MemberEntity member=new MemberEntity();

        member.setId(IdUtil.objectId());
        member.setName("西决");
        member.setAge(99);
        member.setOuther("这个属性将被忽略加签！");
        member.setTimestamp(String.valueOf(System.currentTimeMillis()));

        // 对称加密,加签
        String signStr = SignPlusUtils.signRsa(publicKey,SignPlusUtils.getAllParams(member), null);

        //System.out.println("sign:"+signStr);

        // 把签名结果放入请求参数中
        member.setSign(signStr);

        //请求
        HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
        headers.put("appid", appId);

        //发送get请求并接收响应数据
        //String result = HttpUtil.createGet(apiUrl).addHeaders(headers).form(data).execute().body();
        //发送post请求并接收响应数据
        Map<String,Object> convert = Convert.convert(Map.class, member);
        String result = HttpUtil.createGet(apiUrl).addHeaders(headers).form(convert).execute().body();
        System.out.println(result);

        RequestEntity entity = Convert.convert(RequestEntity.class, JSONUtil.parse(result));

        return entity;
    }

}
